const ModbusRTU = require("modbus-serial");
const client = new ModbusRTU();

// --- 需要您填写的信息 ---
const ipAddress = "127.0.0.1";              // 替换成您的设备IP地址
const port = 502;                         // 替换成您的设备端口 (通常是 502)
const unitId = 1;                         // 替换成您的设备 Modbus ID (通常是 1)


//1.将扫码信号置为0
//2.将加工完成信号置为0
//3.观察PLC是否能正确处理
async function test(){
    try {
        // 连接到设备
        await client.connectTCP(ipAddress, { port: port });
        client.setID(unitId);
        console.log(`Connected to ${ipAddress}:${port}`);
        
        // 读取当前信号状态，用于后续比较
        console.log("读取当前信号状态...");
        const initialScanSignal1 = await client.readHoldingRegisters(8130, 1);
        const initialScanSignal2 = await client.readHoldingRegisters(8180, 1);
        const initialProcessSignal1 = await client.readHoldingRegisters(8140, 1);
        const initialProcessSignal2 = await client.readHoldingRegisters(8190, 1);
        
        console.log("当前扫码信号状态 - 工位1:", initialScanSignal1.data[0], "工位2:", initialScanSignal2.data[0]);
        console.log("当前加工完成信号状态 - 工位1:", initialProcessSignal1.data[0], "工位2:", initialProcessSignal2.data[0]);
        
        // 1. 将扫码信号置为0
        console.log("正在将扫码信号置为0...");
        await client.writeRegister(8130, 0); // 工位1扫码信号
        await client.writeRegister(8180, 0); // 工位2扫码信号
        console.log("扫码信号已置为0");
        
        // 2. 将加工完成信号置为0
        console.log("正在将加工完成信号置为0...");
        await client.writeRegister(8140, 0); // 工位1加工完成信号
        await client.writeRegister(8190, 0); // 工位2加工完成信号
        console.log("加工完成信号已置为0");
        
        // 3. 等待并观察PLC处理结果
        console.log("等待PLC处理...");
        await new Promise(resolve => setTimeout(resolve, 2000));
        
        // 读取处理后的状态
        const finalScanSignal1 = await client.readHoldingRegisters(8130, 1);
        const finalScanSignal2 = await client.readHoldingRegisters(8180, 1);
        const finalProcessSignal1 = await client.readHoldingRegisters(8140, 1);
        const finalProcessSignal2 = await client.readHoldingRegisters(8190, 1);
        
        console.log("处理后扫码信号状态 - 工位1:", finalScanSignal1.data[0], "工位2:", finalScanSignal2.data[0]);
        console.log("处理后加工完成信号状态 - 工位1:", finalProcessSignal1.data[0], "工位2:", finalProcessSignal2.data[0]);
        
        // 检查PLC是否正确处理了信号重置
        if (finalScanSignal1.data[0] === 0 && finalScanSignal2.data[0] === 0 && 
            finalProcessSignal1.data[0] === 0 && finalProcessSignal2.data[0] === 0) {
            console.log("PLC正确处理了信号重置");
        } else {
            console.log("PLC处理信号重置异常，请检查");
        }
        
    } catch (e) {
        console.error("测试出错:", e.message);
    } finally {
        if (client.isOpen) client.close();
        console.log("测试完成，连接已关闭");
    }
}


test()